﻿using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace es.tools.config
{
    /// <summary>
    /// json配置文件操作工具
    /// </summary>
    public static class GenericBsonConfig
    {
        /// <summary>
        /// 储存对象返回byte[]
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] Save(object obj)
        {
            //object不能直接bson序列化，需要提供类型
            return obj.ToBson(obj.GetType());
        }

        /// <summary>
        /// 储存对象返回byte[]
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static byte[] Save(object obj, BsonBinaryWriterSettings settings)
        {
            return obj.ToBson(obj.GetType(), settings);
        }


        /// <summary>
        /// 储存对象,保存到文件路径
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="filePath"></param>
        public static void Save(object obj, string filePath)
        {
            byte[] bson = Save(obj);
            File.WriteAllBytes(filePath, bson);
        }

        /// <summary>
        /// 储存对象,保存到文件路径
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="filePath"></param>
        /// <param name="settings"></param>
        public static void Save(object obj, string filePath, BsonBinaryWriterSettings settings)
        {
            byte[] bson = Save(obj, settings);
            File.WriteAllBytes(filePath, bson);
        }



        /// <summary>
        /// 从文件加载 
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static T Load<T>(string filePath) where T : new()
        {
            return LoadFromBuffer<T>(File.ReadAllBytes(filePath));
        }


        /// <summary>
        /// 从BSON缓存加载
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="buf"></param>
        /// <returns></returns>
        public static T LoadFromBuffer<T>(byte[] buf) where T : new()
        {
            return BsonSerializer.Deserialize<T>(buf);
        }

        /// <summary>
        /// 从BSON缓存加载
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="buf"></param>
        /// <returns></returns>
        public static object LoadFromBuffer<T>(Type t, byte[] buf) where T : new()
        {
            return BsonSerializer.Deserialize(buf, t);
        }
    }
}
